package com.tyl.controller;


import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.aliyun.oss.OSS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tyl.ResultEntity;
import com.tyl.config.OSSConfig;
import com.tyl.entity.Brand;
import com.tyl.entity.BrandJoinCategory;
import com.tyl.entity.CategoryBrandRelation;
import com.tyl.service.IBrandService;
import com.tyl.service.ICategoryBrandRelationService;
import lombok.SneakyThrows;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.multipart.MultipartFile;
import rx.internal.util.ExceptionsUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 汤云龙
 * @since 2022-03-23
 */
@RestController
@RequestMapping("/brand")
public class BrandController {
    @Resource
    private OSS client;
    @Value("${imgPath}")
    private String path;
    @Value("${bulkName}")
    private String bulkName;
    @Resource
    private IBrandService brandService;
    @Resource
    private ICategoryBrandRelationService cs;

    //图片上传
    @SneakyThrows
    @PostMapping("/uploadImg")
    public ResultEntity upImg(MultipartFile brandImg) throws IOException {
        //获取图片上传的原始文件名
        String oldImg = brandImg.getOriginalFilename();
        //使用uuid给原始文件起一个id用新的名字接收
        String newImg=UUID.randomUUID().toString()+ oldImg;
        client.putObject(bulkName, newImg, brandImg.getInputStream());
        //https://tylmyupimg.oss-cn-beijing.aliyuncs.com/R-C%20%281%29.jpg
        String result="https://"+bulkName+"."+OSSConfig.ENDPOINT+"/"+newImg;
        return ResultEntity.ok(result);
    }
    @PostMapping("/add")
    public ResultEntity Add(@RequestBody Brand brand){
        brandService.save(brand);
        return ResultEntity.ok();
    }
    @GetMapping("OutExcel")
    public void OutExcel(HttpServletResponse response) throws Exception {
        //excel的文件导出
        //指定response的响应格式是一个附件
        response.setHeader("content-disposition","attachment;fileName="+ URLEncoder.encode("所有品牌.xls","utf-8"));
        //获取所有的品牌信息
        List<Brand> brandList = brandService.list();
        //通过工具类进行导出
        ExportParams params=new ExportParams("所有品牌列表","brands");
        //导出的参数
        Workbook workbook = ExcelExportUtil.exportExcel(params, Brand.class, brandList);
        //响应到response流里面
        workbook.write(response.getOutputStream());
    }
    @PostMapping("/importExcel")
    //根据excel表格的数据进行导入,参数就是前端传来的excel文件
    public ResultEntity importExcel(MultipartFile excelFile) throws Exception {
        //指定这个excel的基本设置
        ImportParams params=new ImportParams();
        //指定excel表格的标题只有一行
        params.setTitleRows(1);
        //指定excel的表格的表头有一行
        params.setHeadRows(1);
        //导入,返回一个list集合，这个集合里面存放的就是我们excel表格里面的品牌数据
        List<Brand> brandList = ExcelImportUtil.importExcel(excelFile.getInputStream(), Brand.class, params);
        brandService.saveBatch(brandList);
        return ResultEntity.ok("批量插入成功");
    }
    @DeleteMapping("/delete/{brandId}")
    public ResultEntity deleteById(@PathVariable("brandId") Integer brandId){
        //删除品牌
        brandService.removeById(brandId);
        return ResultEntity.ok("删除成功");
    }
    @GetMapping("/selectOne/{brandId}")
    public ResultEntity selectBrand(@PathVariable("brandId") Integer brandId){
        //根据Id查询
        Brand brand = brandService.getById(brandId);
        return ResultEntity.ok(brand);
    }
    @PutMapping("/update")
    public ResultEntity updateBrand(@RequestBody Brand brand){
        QueryWrapper<Brand> brandQueryWrapper = new QueryWrapper<>();
        brandQueryWrapper.eq("brand_id",brand.getBrandId());
        brandService.update(brand, brandQueryWrapper);
        return ResultEntity.ok("修改成功");
    }
    @PostMapping("/relaCate")
    public ResultEntity relaCate(@RequestBody BrandJoinCategory brandJoinCategory){
        //循环得到所有的商品类别
        for (Long categoryId:brandJoinCategory.getCateIds()){
            CategoryBrandRelation cb = new CategoryBrandRelation();
            //给品牌赋予当前要id
            cb.setBrandId(brandJoinCategory.getBrandId());
            //给商品赋予要赋予的id
            cb.setCategoryId(categoryId);
            cs.save(cb);
        }
        return ResultEntity.ok("关联成功");

    }


}

